/**
 * 首页
 */

import React, {Component} from 'react';
import {
    StyleSheet,
    View,
    ListView,
    Dimensions,
    TouchableOpacity,
    Image,
    Text,
    PixelRatio,
    RefreshControl,
    Platform
} from 'react-native';

import RequestUtil from '../../src/utils/RequestUtil';
import HomeParseData from './HomeParseData';
import ImageScrollView from './itemCells/ImageScrollView'
import HomeIconView from './itemCells/HomeIconView'
import HomeGoodView from './itemCells/HomeGoodView'
import HomeImageCellView from './itemCells/HomeImageCellView'
import HomeGuessLikeView from './itemCells/HomeGuessLikeView'
import HomeMessageView from './itemCells/HomeMessageView'
import HomeSecKillView from './itemCells/HomeSecKillView'
import NavigationBar from 'react-native-navbar';
import WebViewRN from '../commentView/WebViewRN'

var allData = {};
var WindowWidth = Dimensions.get('window').width;
var WindowHeight = Dimensions.get('window').height;
var MixHeight = Platform.OS == 'ios'?(64+49):(64+49+10);


export default class Home extends Component {

  // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            dataSource: new ListView.DataSource({rowHasChanged:(r1,r2) => ri !== r2}),
            refreshing:false
        };
    }
    _renderSectionHeader(sectionData,sectionId) {
        if(sectionId == 'carousel' || sectionId == 'icon') {
            return (
                <View style={{height:0}}>
                </View>
            );
        }
        var titleData = allData[sectionId]['title']['title'];
        if (titleData == null) {
            return (
                <View style={{backgroundColor:'#F2F2F2',height: 3}}>
                </View>
            );
        }else {
            return(
                <View style={{backgroundColor:'white',height: 43,justifyContent:'center'}}>
                    <View style={{backgroundColor:'#F2F2F2',height:3,position:'absolute',left:0,right:0,top:0}}/>
                    <Text style={{fontSize:16,color:'#6E6E6E',marginLeft:10}}>{titleData}</Text>
                    <View style={{width:WindowWidth,height:1/PixelRatio.get(),backgroundColor:'#E6E6E6',position:'absolute',left:0,bottom:0}}/>
                </View>
            );
        }

    }
    _bannerImageClick(imageInfo){
        console.log(imageInfo);
    }

    _renderRow(rowData,sectionId,rowId) {

        if(sectionId == 'carousel') {
            //轮播图
            var imageArray = allData[sectionId][sectionId];
            var imageUrlArray = [];
            for(var i = 0; i< imageArray.length; i++) {
                var info = imageArray[i];
                var imageUrl = 'http://demo.jiuyunda.net:24799'+info['img'].toString();
                imageUrlArray.push(imageUrl);
            }
            return (<ImageScrollView style={styles.imageScroll} imageUrlArray={imageUrlArray} imageClick={(index)=>{
                    var imageDataArray = allData['carousel']['carousel'];
                    var imageData = imageDataArray[index];
                    var event_mark = imageData['event_mark'];
                    var nav = global.nav;
                    if (event_mark == 0){
                        return;
                    }
                    if  (event_mark == 1){
                        return;
                    }
                    if  (event_mark == 2){
                        if (nav){
                            nav.push({
                                name: 'webView',
                                component: WebViewRN,
                                params:{
                                    url:imageData['event_memo']
                                }
                            })
                        }
                        return;
                    }
                    if  (event_mark == 3){
                        return;
                    }


                }
            }/>);
        }else if(sectionId == 'icon') {
            //icon
            var iconArray = allData[sectionId][sectionId];
            return (<HomeIconView style={styles.iconView} iconArray={iconArray} />)
        }else if(sectionId == 'singlemap'){
            /** 一图 singlemap */
            var singleMap = allData[sectionId][sectionId];
            var imageUrl = 'http://demo.jiuyunda.net:24799'+singleMap['img'].toString();
            return (
                  <TouchableOpacity activeOpacity={0.8} >
                      <Image style={styles.singleMap} source={{uri:imageUrl}} />
                  </TouchableOpacity>
            );
        }else if(sectionId == 'hot_sale_good'){
            var goodArray = allData[sectionId][sectionId];
            var doubleGood = [];
            doubleGood.push(goodArray[rowId*2]);
            doubleGood.push(goodArray[rowId*2+1]);
            return (
                <HomeGoodView style={styles.goodView} goods={doubleGood} />
            );
        }else if(sectionId == 'fourspace'){
            var imageData = allData[sectionId][sectionId];
            return(
                <HomeImageCellView imageStyle='fourspace' style={styles.fourspace} imageArray={imageData}/>
            );
        }else if(sectionId == 'subject_2_picture'){
            var imageData = allData[sectionId][sectionId];
            return(
                <HomeImageCellView imageStyle='subject_2_picture' style={styles.subject_2_picture} imageArray={imageData}/>
            );
        }else if(sectionId == 'subject_3_l_picture' || sectionId == 'subject_3_r_picture'){
            var imageData = allData[sectionId][sectionId];
            return(
                <HomeImageCellView imageStyle={sectionId} style={styles.subject_3_picture} imageArray={imageData}/>
            );
        }else if(sectionId == 'subject_product_list') {
            var goodArray = allData[sectionId][sectionId];
            var doubleGood = [];
            doubleGood.push(goodArray[rowId*2]);
            doubleGood.push(goodArray[rowId*2+1]);
            return (
                <HomeGoodView style={styles.goodView} goods={doubleGood} />
            );
        }else if(sectionId == 'guess_you_like') {
            var goodArray = allData[sectionId][sectionId];
            return(
                <HomeGuessLikeView style={styles.guess_you_like} goodArray={goodArray}/>
            );
        }else if(sectionId == 'announcement') {
            var messageArray = allData[sectionId][sectionId];
            return(
                <HomeMessageView style={styles.announcement} messageArray={messageArray} messageClick={(url)=>{
                    var nav = global.nav;
                    if (nav){
                        nav.push({
                            name: 'webView',
                            component: WebViewRN,
                            params:{
                                url:url
                            }
                        })
                    }
                }}/>
            );
        }else if(sectionId == 'sec_kill_round_info') {
            var killData = allData[sectionId][sectionId];
            return(
                <HomeSecKillView style={styles.HomeSecKillView} killData={killData}/>
            );
        }
        return (
            <View style={styles.row}>

            </View>
        );
    }
    _renderFooter(){
        return (
            <View style={{height: 30,justifyContent:'center',flexDirection: 'row',flexWrap: 'wrap',alignItems:'center'}}>
                <View style={{marginRight:5,backgroundColor:'#AAAAAA',height:1/PixelRatio.get(),width:80}}/>
                <Text style={{color:'#787878',fontSize:12}}>{'我是有底线的'}</Text>
                <View style={{marginLeft:5,backgroundColor:'#AAAAAA',height:1/PixelRatio.get(),width:80}}/>
            </View>
        );
    }


    _renderSearchView(){
        return(
            <TouchableOpacity activeOpacity={0.8}>
                <View style={{width:WindowWidth-120,height:30,backgroundColor:'rgba(245, 245, 245, 0.3)',borderRadius:15,flexDirection:'row',alignItems:'center',marginLeft:40}}>
                    <Text style={{marginLeft:10,fontSize:14,color:'white',width:150}}>输入商家、产品名称</Text>
                    <Image style={{width:20,height:20,position:'absolute',top:5,right:10}} source={require('../resoure/home/gydSearchW@3x.png')}/>
                </View>
            </TouchableOpacity>
        );
    }
    _renderNavLeftButton(){
        return(
            <TouchableOpacity activeOpacity={0.8}>
                <View style={{flexDirection:'row',alignItems:'center',height:44,width:80}}>
                    <Image style={{width:20,height:20,marginLeft:5}} source={require('../resoure/home/position@3x.png')}/>
                    <Text style={{fontSize:15,color:'white'}}> 郑州市</Text>
                </View>
            </TouchableOpacity>
        );
    }

    render() {
        return (
            <View>
                <NavigationBar
                    tintColor='#FF6261'
                    statusBar={{style:'light-content'}}
                    title={this._renderSearchView()}
                    leftButton={this._renderNavLeftButton()}
                />
                <ListView
                    style={styles.listView}
                    dataSource={this.state.dataSource}
                    renderSectionHeader={this._renderSectionHeader.bind(this)}
                    renderRow={this._renderRow.bind(this)}
                    enableEmptySections={true}
                    initialListSize={8}
                    automaticallyAdjustContentInsets={false}
                    scrollRenderAheadDistance={700}
                    pageSize={4}
                    renderFooter={this._renderFooter}
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.refreshing}
                            onRefresh={() => {this._getHomeData()}}
                            title=" "
                        />
                    }
                >
                </ListView>
            </View>
        )
    }

    componentDidMount() {
        this._getHomeData();
    }



    /**
     * 获取数据
     */
    _getHomeData() {
        this.setState({
            dataSource: this.state.dataSource,
            refreshing:true
        });
        var requestUtil = new RequestUtil();
        var bid = global.BID;
        var cid = global.CID;
        if (cid != undefined){
            cid = '&customer_id='+cid;
        }else{
            cid = '';
        }
        requestUtil.init()
            .setUrl('http://demo.jiuyunda.net:24799/api/v2/home_page/index_for_new?userinfo_id='+bid+cid)
            .setMethod('GET')
            .setOvertime(30*1000)
            .setHeader({
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }).dofetch()
            .then((data) => {
                var errorcode = data['status'];
                if(errorcode) {

                }else {
                    ///解析数据
                    var parseData = new HomeParseData();
                    //解析数据
                    var returnData = parseData.parseData(data);
                    var getSectionData = (dataBlob, sectionID) => {
                        return sectionID;
                    };
                    var getRowData = (dataBlob, sectionID, rowID) => {
                        return rowID;
                    };
                    var dataSource = new ListView.DataSource({
                        getRowData: getRowData,
                        getSectionHeaderData : getSectionData,
                        rowHasChanged: (row1, row2) => row1 !== row2,
                        sectionHeaderHasChanged: (s1, s2) => s1 !== s2
                    });
                    allData = returnData['dataBlob'];
                    console.log(returnData);
                    this.setState({
                        dataSource: dataSource.cloneWithRowsAndSections(returnData['dataBlob'], returnData['sectionIDs'], returnData['rowIDs']),
                        refreshing:false
                    });
                }
            })
            .catch((error) => {
               console.log(('home => catch'));
            });
    }
}
const styles = StyleSheet.create({
    listView: {
        flex:1,
        backgroundColor: '#F2F2F2',
        width:WindowWidth,
        height:WindowHeight-MixHeight
    },
    row:{
        backgroundColor:'blue',
        height: 60
    },
    imageScroll: {
        width:WindowWidth,
        height:WindowWidth/375.0*120
    },
    iconView: {
        width:WindowWidth,
        height:WindowWidth/2,
        backgroundColor:'white'
    },
    singleMap: {
        width:WindowWidth,
        height:70,
        backgroundColor:'white'
    },
    goodView: {
        width: WindowWidth,
        height: (WindowWidth - 3)/2.0 + 95,
        backgroundColor: 'white'
    },
    fourspace:{
        width: WindowWidth,
        height: WindowWidth/375*180
    },
    subject_2_picture:{
        width: WindowWidth,
        height: WindowWidth/375*110,
        backgroundColor:'white'
    },
    subject_3_picture: {
        width: WindowWidth,
        height: WindowWidth/375*220,
        backgroundColor:'white'
    },
    guess_you_like:{
        width: WindowWidth,
        height: 170,
        backgroundColor:'white'
    },
    announcement:{
        width: WindowWidth,
        height: 50,
        backgroundColor:'white'
    },
    HomeSecKillView:{
        width: WindowWidth,
        height: 125 + (WindowWidth - 60)/3.0,
        backgroundColor:'white'
    }
});


